package dating.controller;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dating.model.User;
import dating.service.UserServiceLocal;

abstract public class Application extends HttpServlet {

	@EJB
	protected UserServiceLocal userService;
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -1234183045213301077L;

	protected void render(String template, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("contents", template);
		
		request.getRequestDispatcher("WEB-INF/views/layout.jsp").forward(request, response);
	}
	
	protected boolean isLogged(HttpServletRequest req){
		if(getLoggedUser(req) != null) {
			return true;
		}
		return false;
	}
	
	protected void requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException{
		if(!isLogged(request)){
			response.sendRedirect("login");
		}
	}
	
	protected User getLoggedUser(HttpServletRequest req){
		User user = (User) req.getAttribute("logged");
		return user;
	}
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
	        throws ServletException, IOException {
			
			Long id = (Long) req.getSession().getAttribute("user_id");
			if(id != null) {
				User user = userService.findByPK(id);
				req.setAttribute("logged", user);
			}
			
			super.service(req, resp);
	    }
}
